// server/server.go
package server

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/fx"
)

type Server struct {
	httpServer *http.Server
}

func NewServer(lc fx.Lifecycle, engine *gin.Engine) *Server {
	srv := &Server{
		httpServer: &http.Server{
			Addr:    ":8080",
			Handler: engine,
		},
	}

	lc.Append(fx.Hook{
		OnStart: func(ctx context.Context) error {
			fmt.Println("Starting server on :8080")
			go func() {
				if err := srv.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
					fmt.Printf("Server failed to start: %v\n", err)
				}
			}()

			// 添加启动成功提示
			fmt.Println("Server startup process initiated")
			return nil
		},
		OnStop: func(ctx context.Context) error {
			fmt.Println("Shutting down server")
			ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
			return srv.httpServer.Shutdown(ctx)
		},
	})

	fmt.Println("Server instance created")
	return srv
}
